package io.gitee.bowen_lee.netty.netty;

import java.net.InetSocketAddress;

import io.gitee.bowen_lee.netty.bowen.client.MyChannelHandle;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ClientMain {
  public static void main(String[] args) throws InterruptedException {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    Bootstrap bs = new Bootstrap();
    ChannelFuture connect = bs.group(group)
        .channel(NioSocketChannel.class)
        // .handler(new ChannelInit())
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new MyChannelHandle() {

              @Override
              public void println(ChannelHandlerContext ctx, String msgStr) {
                // 客户端收到服务端的‘收到’，回复Bye Bye!
                if ("received!".equals(msgStr)) {
                  System.out.println("发送 Bye Bye!");
                  ctx.writeAndFlush(Unpooled.copiedBuffer("Bye Bye!".getBytes()));
                }
              }

            });
          }
        })
        .connect(new InetSocketAddress("127.0.0.1", 9090));

    Channel client = connect.sync().channel();

    client.writeAndFlush(Unpooled.copiedBuffer("hello world".getBytes())).sync();
    System.out.println("发送 hello world");

    client.closeFuture().sync();

  }
}
